package com.ujs.controller;


import com.ujs.pojo.Role;
import com.ujs.pojo.UserInfo;
import com.ujs.service.UserInfoService;
import com.ujs.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;


    @RequestMapping("/findAll")
    @Secured("ROLE_ADMIN")
    public String findAllByPage(Model model,@RequestParam(name = "page", required = true, defaultValue = "1") Integer page,
                                @RequestParam(name = "pageSize", required = true, defaultValue = "4") Integer pageSize){
        List<UserInfo> list = userInfoService.findAll();
        PageUtil<UserInfo> pageInfo = new PageUtil<>(page, pageSize, list);
        List<UserInfo> userList = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("userList",userList);
        return "user-list";
    }

    @GetMapping("/user-add")
    public String userAdd(){
        return "user-add";
    }

    @PostMapping("/save")
    public String save(Model model,UserInfo user){
        userInfoService.save(user);
        return "redirect:findAll";
    }

    @RequestMapping("/findById")
    public String findById(Model model,String userId){
        UserInfo userInfo = userInfoService.findById(userId);
        model.addAttribute("userInfo", userInfo);
        return "user-show";
    }

    @RequestMapping("/findUserByIdAndAllRole")
        public String findUserByIdAndAllRole(Model model,@RequestParam(name = "userId",required = true) String userId){
        UserInfo userInfo = userInfoService.findById(userId);
        List<Role>roleList= userInfoService.findOtherRoles(userId);
        model.addAttribute("userInfo",userInfo);
        model.addAttribute("roleList", roleList);
        return "user-role-add";
        }

        @RequestMapping("/addRoleToUser")
        public String addRoleToUser(@RequestParam(name="userId",required = true)String userId,
                                    @RequestParam(name="ids",required = true)String []roleIds){
        userInfoService.addRoleToUser(userId,roleIds);
        return "redirect:findAll";
        }
}
